<template>
  <div class="admin-dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="12" :lg="6">
        <el-card class="stats-card merchant-card">
          <div class="card-content">
            <div class="card-icon">
              <i class="el-icon-share"></i>
            </div>
            <div class="card-info">
              <div class="card-title">商家总数</div>
              <div class="card-value">{{ statistics.merchantCount || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="12" :sm="12" :lg="6">
        <el-card class="stats-card user-card">
          <div class="card-content">
            <div class="card-icon">
              <i class="el-icon-user"></i>
            </div>
            <div class="card-info">
              <div class="card-title">用户总数</div>
              <div class="card-value">{{ statistics.userCount || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="12" :sm="12" :lg="6">
        <el-card class="stats-card salesman-card">
          <div class="card-content">
            <div class="card-icon">
              <i class="el-icon-s-custom"></i>
            </div>
            <div class="card-info">
              <div class="card-title">业务员总数</div>
              <div class="card-value">{{ statistics.salesmanCount || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="12" :sm="12" :lg="6">
        <el-card class="stats-card agent-card">
          <div class="card-content">
            <div class="card-icon">
              <i class="el-icon-office-building"></i>
            </div>
            <div class="card-info">
              <div class="card-title">区域代理总数</div>
              <div class="card-value">{{ statistics.agentCount || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主要内容区域 - 左右两列布局 -->
    <div class="main-content-wrapper">
      <!-- 左侧列 -->
      <div class="content-column left-column">
        <!-- 最近订单 -->
        <el-card class="content-card recent-orders-card">
          <div slot="header" class="card-header">
            <span>最近订单</span>
            <router-link to="/admin/order-management" class="view-more">查看更多</router-link>
          </div>
          <configurable-table
            :columns="recentOrdersColumns"
            :data="recentOrders"
            :loading="ordersLoading"
            :show-index="false"
            max-height="360"
            style="width: 100%">
            <template #status="{ row }">
              <el-tag :type="getStatusTagType(row.statue)" size="mini">
                {{ getStatusText(row.statue) }}
              </el-tag>
            </template>
          </configurable-table>
        </el-card>

        <!-- 各区域每月贡献值 -->
        <el-card class="content-card chart-card">
          <div slot="header" class="card-header">
            <span>各区域每月贡献值</span>
            <el-button type="text" @click="refreshContribution" :loading="contributionLoading">刷新</el-button>
          </div>
          <div class="chart-placeholder" v-loading="contributionLoading">
            <div v-if="!contributionData.length" class="no-data">
              <i class="el-icon-data-analysis"></i>
              <p>暂无数据</p>
            </div>
            <div v-else class="contribution-chart">
              <div class="chart-title">积分数量</div>
              <!-- 这里可以集成 ECharts 或其他图表库 -->
              <div class="simple-chart">
                <div v-for="(item, index) in contributionData" :key="index" class="chart-bar">
                  <div class="bar-label">{{ item.regionName }}</div>
                  <div class="bar-container">
                    <div class="bar-fill" :style="{ width: getBarWidth(item.points) + '%' }"></div>
                    <span class="bar-value">{{ item.points }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧列 -->
      <div class="content-column right-column">
        <!-- 待审核事项 -->
        <el-card class="content-card">
          <div slot="header" class="card-header">
            <span>待审核事项</span>
          </div>
          <div class="audit-items">
            <div class="audit-item" @click="goToMerchantAudit">
              <div class="audit-icon merchant-icon">
                <i class="el-icon-share"></i>
              </div>
              <div class="audit-info">
                <div class="audit-title">商家审核</div>
                <div class="audit-count">{{ auditCounts.merchantCount || 0 }}个待审核</div>
              </div>
            </div>

            <div class="audit-item" @click="goToWithdrawAudit">
              <div class="audit-icon withdraw-icon">
                <i class="el-icon-money"></i>
              </div>
              <div class="audit-info">
                <div class="audit-title">提现审核</div>
                <div class="audit-count">{{ auditCounts.withdrawCount || 0 }}个待审核</div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 各区域代理当月积分贡献 -->
        <el-card class="content-card chart-card">
          <div slot="header" class="card-header">
            <span>各区域代理当月积分贡献</span>
            <el-button type="text" @click="refreshContribution" :loading="contributionLoading">刷新</el-button>
          </div>
          <div class="chart-placeholder" v-loading="contributionLoading">
            <div class="no-data">
              <i class="el-icon-pie-chart"></i>
              <p>暂无数据</p>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { getHomeStatistics, getRecentOrders, getMerchantAuditCount, getWithdrawAuditCount, getContributionData } from '@/api/aggregation'

export default {
  name: 'AdminDashboard',
  data() {
    return {
      // 统计数据
      statistics: {
        merchantCount: 0,
        userCount: 0,
        salesmanCount: 0,
        agentCount: 0
      },

      // 最近订单
      recentOrders: [],
      ordersLoading: false,

      // 审核统计
      auditCounts: {
        merchantCount: 0,
        withdrawCount: 0
      },

      // 贡献数据
      contributionData: [],
      contributionLoading: false
    }
  },

  computed: {
    // 最近订单表格列配置
    recentOrdersColumns() {
      return [
        {
          prop: 'id',
          label: '订单ID',
          minWidth: 100,
          render: (h, { row }) => {
            return h('span', { class: 'order-id' }, row.id)
          }
        },
        {
          prop: 'merchantName',
          label: '商家',
          minWidth: 120,
          render: (h, { row }) => {
            return h('span', { class: 'merchant-name' }, row.merchantName || '-')
          }
        },
        {
          prop: 'amount',
          label: '金额',
          minWidth: 100,
          render: (h, { row }) => {
            return h('span', { class: 'amount' }, `¥${this.formatAmount(row.amount)}`)
          }
        },
        {
          prop: 'statue',
          label: '状态',
          minWidth: 80,
          slot: 'status'
        },
        {
          prop: 'createTime',
          label: '时间',
          render: (h, { row }) => {
            return h('span', { class: 'create-time' }, this.formatTime(row.createTime))
          }
        }
      ]
    }
  },

  mounted() {
    this.loadAllData()
  },

  methods: {
    // 加载所有数据
    async loadAllData() {
      await Promise.all([
        this.loadStatistics(),
        this.loadRecentOrders(),
        this.loadAuditCounts(),
        this.loadContributionData()
      ])
    },

    // 加载统计数据
    async loadStatistics() {
      try {
        Logger.log('=== 加载首页统计数据 ===')
        const response = await getHomeStatistics()

        if (response.code === 0) {
          this.statistics = response.data || {}
          Logger.log('统计数据:', this.statistics)
        } else {
          Logger.error('获取统计数据失败:', response.msg)
        }
      } catch (error) {
        Logger.error('加载统计数据失败:', error)
        // 如果接口不存在，使用默认值
        this.statistics = {
          merchantCount: 0,
          userCount: 0,
          salesmanCount: 0,
          agentCount: 0
        }
      }
    },

    // 加载最近订单
    async loadRecentOrders() {
      this.ordersLoading = true
      try {
        Logger.log('=== 加载最近订单 ===')
        const response = await getRecentOrders({ pageIndex: 1, pageSize: 5 })

        if (response.code === 0) {
          this.recentOrders = response.data.list || []
          Logger.log('最近订单:', this.recentOrders)
        } else {
          this.recentOrders = []
        }
      } catch (error) {
        Logger.error('加载最近订单失败:', error)
        this.recentOrders = []
      } finally {
        this.ordersLoading = false
      }
    },

    // 加载审核统计
    async loadAuditCounts() {
      try {
        Logger.log('=== 加载审核统计 ===')

        // 并行获取商家审核和提现审核的统计数据
        const [merchantResponse, withdrawResponse] = await Promise.all([
          getMerchantAuditCount(),
          getWithdrawAuditCount()
        ])

        // 处理商家审核统计
        let merchantCount = 0
        if (merchantResponse.code === 0) {
          merchantCount = merchantResponse.data.total || 0
          Logger.log('商家待审核数量:', merchantCount)
        }

        // 处理提现审核统计
        let withdrawCount = 0
        if (withdrawResponse.code === 0) {
          withdrawCount = withdrawResponse.data.total || 0
          Logger.log('提现待审核数量:', withdrawCount)
        }

        this.auditCounts = {
          merchantCount: merchantCount,
          withdrawCount: withdrawCount
        }

        Logger.log('审核统计完成:', this.auditCounts)
      } catch (error) {
        Logger.error('加载审核统计失败:', error)
        this.auditCounts = { merchantCount: 0, withdrawCount: 0 }
      }
    },

    // 加载贡献数据
    async loadContributionData() {
      this.contributionLoading = true
      try {
        Logger.log('=== 加载贡献数据 ===')
        const response = await getContributionData()

        if (response.code === 0) {
          this.contributionData = response.data || []
          Logger.log('贡献数据:', this.contributionData)
        } else {
          this.contributionData = []
        }
      } catch (error) {
        Logger.error('加载贡献数据失败:', error)
        this.contributionData = []
      } finally {
        this.contributionLoading = false
      }
    },

    // 刷新贡献数据
    refreshContribution() {
      this.loadContributionData()
    },

    // 格式化金额
    formatAmount(amount) {
      if (!amount) return '0.00'
      return (amount / 100).toFixed(2)
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '-'
      return time.split(' ')[0] // 只显示日期部分
    },

    // 获取状态标签类型
    getStatusTagType(status) {
      const statusMap = {
        0: 'warning',  // 待支付
        1: 'success',  // 已支付
        '-1': 'info' // 已取消
      }
      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        '-1': '已取消'
      }
      return statusMap[status] || '未知'
    },

    // 获取柱状图宽度
    getBarWidth(points) {
      if (!points || points === 0) return 0
      const maxPoints = Math.max(...this.contributionData.map(item => item.points))
      return (points / maxPoints) * 100
    },

    // 跳转到商家审核
    goToMerchantAudit() {
      this.$router.push('/admin/merchant-audit')
    },

    // 跳转到提现审核
    goToWithdrawAudit() {
      this.$router.push('/admin/withdraw-audit')
    }
  }
}
</script>

<style lang="scss" scoped>
.admin-dashboard {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 84px);
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .card-content {
    display: flex;
    align-items: center;
    padding: 10px;

    .card-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;

      i {
        font-size: 24px;
        color: white;
      }
    }

    .card-info {
      flex: 1;

      .card-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
      }

      .card-value {
        font-size: 24px;
        font-weight: bold;
        color: #333;
      }
    }
  }

  &.merchant-card .card-icon {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }

  &.user-card .card-icon {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  }

  &.salesman-card .card-icon {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  }

  &.agent-card .card-icon {
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  }
}

/* 主要内容区域 - 左右两列布局 */
.main-content-wrapper {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

@media (max-width: 1200px) {
  .main-content-wrapper {
    flex-direction: column;
  }
}

.content-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.content-column.left-column,
.content-column.right-column {
  flex: 1;
  min-width: 0;
}

.content-row {
  margin-bottom: 20px;
}

.content-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .view-more {
      color: #409eff;
      text-decoration: none;
      font-size: 12px;

      &:hover {
        text-decoration: underline;
      }
    }
  }

  &.recent-orders-card {
    ::v-deep .el-card__body {
      max-height: 400px;
      overflow: auto;
    }

    // 隐藏最近订单表格的表头
    ::v-deep .el-table__header-wrapper {
      display: none;
    }
  }
}

.audit-items {
  .audit-item {
    display: flex;
    align-items: center;
    padding: 15px 0;
    cursor: pointer;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      background-color: #f8f9fa;
      margin: 0 -20px;
      padding-left: 20px;
      padding-right: 20px;
    }

    .audit-icon {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;

      i {
        font-size: 20px;
        color: white;
      }

      &.merchant-icon {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      &.withdraw-icon {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }
    }

    .audit-info {
      flex: 1;

      .audit-title {
        font-size: 16px;
        font-weight: 500;
        color: #333;
        margin-bottom: 5px;
      }

      .audit-count {
        font-size: 14px;
        color: #666;
      }
    }
  }
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .el-button--text{
      padding:0;
    }
  }
  .chart-placeholder {
    height: 300px;
    display: flex;
    align-items: center;
    justify-content: center;

    .no-data {
      text-align: center;
      color: #999;

      i {
        font-size: 48px;
        margin-bottom: 10px;
        display: block;
      }
    }
  }
}

.contribution-chart {
  width: 100%;

  .chart-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 15px;
  }

  .chart-bar {
    margin-bottom: 15px;

    .bar-label {
      font-size: 12px;
      color: #666;
      margin-bottom: 5px;
    }

    .bar-container {
      position: relative;
      height: 20px;
      background-color: #f0f0f0;
      border-radius: 10px;
      overflow: hidden;

      .bar-fill {
        height: 100%;
        background: linear-gradient(90deg, #409eff 0%, #67c23a 100%);
        border-radius: 10px;
        transition: width 0.3s ease;
      }

      .bar-value {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 12px;
        color: #666;
      }
    }
  }
}

// 表格样式优化
.el-table {
  .order-id {
    font-weight: 500;
    color: #409eff;
  }

  .merchant-name {
    color: #333;
  }

  .amount {
    color: #67c23a;
    font-weight: 500;
  }

  .create-time {
    color: #666;
    font-size: 12px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .admin-dashboard {
    padding: 10px;
  }

  .stats-card .card-content {
    padding: 8px;

    .card-icon {
      width: 50px;
      height: 50px;
      margin-right: 10px;

      i {
        font-size: 20px;
      }
    }

    .card-info .card-value {
      font-size: 20px;
    }
  }
}
</style>
